'use client';

import React, { useState } from 'react';
import DepthChart from './DepthChart';
import { useMarketData } from '../hooks/useMarketData';

interface OrderBookEntry {
  price: number;
  amount: number;
  total: number;
}

interface OrderBookProps {
  symbol: string;
  onPriceClick: (price: number) => void;
}

export default function OrderBook({ 
  symbol, 
  onPriceClick 
}: OrderBookProps) {
  const [activeTab, setActiveTab] = useState<'depth' | 'orderbook'>('orderbook');
  
  // 使用币安真实数据
  const { orderBook, currentPrice, loading, error } = useMarketData({
    symbol: symbol.replace('/', ''),  // BTC/USDT -> BTCUSDT
    dataSource: 'binance',
    enableRealtime: true
  });

  // 如果有错误或加载中，使用模拟数据
  const sellOrders: OrderBookEntry[] = orderBook?.sellOrders?.slice(0, 10) || [
    { price: 62450.00, amount: 1.2345, total: 77100.03 },
    { price: 62425.00, amount: 0.8765, total: 54730.16 },
    { price: 62400.00, amount: 2.1234, total: 132467.76 },
    { price: 62375.00, amount: 1.5678, total: 97809.83 },
    { price: 62350.00, amount: 0.9876, total: 61572.86 },
  ];

  const buyOrders: OrderBookEntry[] = orderBook?.buyOrders?.slice(0, 10) || [
    { price: 62325.00, amount: 1.3456, total: 83882.84 },
    { price: 62300.00, amount: 2.0987, total: 130767.61 },
    { price: 62275.00, amount: 0.7654, total: 47664.28 },
    { price: 62250.00, amount: 1.8765, total: 116787.94 },
    { price: 62225.00, amount: 1.1234, total: 69907.37 },
  ];

  const formatNumber = (num: number, decimals = 4) => {
    return num.toFixed(decimals);
  };

  return (
    <div className="bg-white dark:bg-gray-800 rounded-lg shadow-sm border border-gray-200 dark:border-gray-700 h-full">
      {/* 标签页切换 */}
      <div className="flex border-b border-gray-200 dark:border-gray-700">
        <button
          onClick={() => setActiveTab('depth')}
          className={`flex-1 px-4 py-3 text-sm font-medium transition-colors ${
            activeTab === 'depth'
              ? 'text-blue-600 dark:text-blue-400 border-b-2 border-blue-600 dark:border-blue-400 bg-blue-50 dark:bg-blue-900/20'
              : 'text-gray-500 dark:text-gray-400 hover:text-gray-700 dark:hover:text-gray-300'
          }`}
        >
          深度图
        </button>
        <button
          onClick={() => setActiveTab('orderbook')}
          className={`flex-1 px-4 py-3 text-sm font-medium transition-colors ${
            activeTab === 'orderbook'
              ? 'text-blue-600 dark:text-blue-400 border-b-2 border-blue-600 dark:border-blue-400 bg-blue-50 dark:bg-blue-900/20'
              : 'text-gray-500 dark:text-gray-400 hover:text-gray-700 dark:hover:text-gray-300'
          }`}
        >
          订单簿
        </button>
      </div>

      {activeTab === 'depth' ? (
        /* 深度图 */
        <div className="flex-1 overflow-hidden">
          <DepthChart
            symbol={symbol}
            onPriceClick={onPriceClick}
          />
        </div>
      ) : (
        /* 订单簿 */
        <div className="p-4 overflow-y-auto" style={{ height: 'calc(100% - 60px)' }}>
          {/* 状态栏 */}
          <div className="flex items-center justify-between mb-3">
            <div className="flex items-center space-x-2 text-sm text-gray-600 dark:text-gray-400">
              <span>{symbol}</span>
              {loading && <span className="text-blue-500">📡</span>}
              {error && <span className="text-red-500">⚠️</span>}
            </div>
            <span className="text-xs text-green-500">币安实时</span>
          </div>

          {/* 表头 */}
          <div className="grid grid-cols-3 gap-4 text-xs font-medium text-gray-500 dark:text-gray-400 mb-2 pb-2 border-b border-gray-100 dark:border-gray-600">
            <div className="text-right">价格 (USDT)</div>
            <div className="text-right">数量 (BTC)</div>
            <div className="text-right">累计</div>
          </div>

          {/* 卖单 */}
          <div className="mb-4">
            {sellOrders.reverse().map((order, index) => (
              <button
                key={`sell-${index}`}
                onClick={() => onPriceClick(order.price)}
                className="w-full grid grid-cols-3 gap-4 py-1 text-xs hover:bg-red-50 dark:hover:bg-red-900/20 transition-colors group"
              >
                <div className="text-right text-red-600 dark:text-red-400 group-hover:text-red-700 dark:group-hover:text-red-300">
                  {formatNumber(order.price, 2)}
                </div>
                <div className="text-right text-gray-700 dark:text-gray-300">
                  {formatNumber(order.amount)}
                </div>
                <div className="text-right text-gray-500 dark:text-gray-400">
                  {formatNumber(order.total, 2)}
                </div>
              </button>
            ))}
          </div>

          {/* 价差 */}
          <div className="py-2 mb-4 text-center border-t border-b border-gray-100 dark:border-gray-600">
            <div className="text-lg font-semibold text-gray-900 dark:text-white">
              {(currentPrice || 62350.00).toLocaleString()}
            </div>
            <div className="text-xs text-gray-500 dark:text-gray-400">
              ≈ ${(currentPrice || 62350.00).toLocaleString()}
            </div>
          </div>

          {/* 买单 */}
          <div>
            {buyOrders.map((order, index) => (
              <button
                key={`buy-${index}`}
                onClick={() => onPriceClick(order.price)}
                className="w-full grid grid-cols-3 gap-4 py-1 text-xs hover:bg-green-50 dark:hover:bg-green-900/20 transition-colors group"
              >
                <div className="text-right text-green-600 dark:text-green-400 group-hover:text-green-700 dark:group-hover:text-green-300">
                  {formatNumber(order.price, 2)}
                </div>
                <div className="text-right text-gray-700 dark:text-gray-300">
                  {formatNumber(order.amount)}
                </div>
                <div className="text-right text-gray-500 dark:text-gray-400">
                  {formatNumber(order.total, 2)}
                </div>
              </button>
            ))}
          </div>
        </div>
      )}
    </div>
  );
}
